<template>
  <view>
    <!-- 第一部分：正方形的view标签，包含圆形和时间、距离信息 -->
    <view class="square-view">
      <view class="circle">
        <text>{{ currentTime }}</text>
      </view>
      <text v-if="punchRange.addr">当前位置：{{ punchRange.addr }}</text>
      <text class="distance">{{ distanceText }}</text>
    </view>
    <!-- 第二部分：打卡按钮 -->
    <button type="primary" @click="punchCard">打卡</button>
    <!-- <button type="primary" @click="chooseVideo">录视频</button> -->

    <!-- 原有的地图和定位组件 -->
    <mumu-getlocation ref="muLocation"></mumu-getlocation>
  </view>
</template>

<script>
import mumuGetlocation from "@/uni_modules/mumu-getlocation/components/mumu-getlocation/mumu-getlocation.vue";
import {
  getProjectInfo,
  // 假设这里有一个获取距离的接口
  getDistance,
} from "@/api/api.js";

import { attendanceIn } from "@/api/attendance.js";
import {wgs84togcj02 } from "@/utils/common.js";

export default {
  name: "ClockIn",
  data() {
    return {
      // 这里放置数据
      userId: uni.getStorageSync("userId"),
      projectId: uni.getStorageSync("projectId"),
      mapLocation: null,
      punchRange: {
        type: "",
        addr: "",
        city: "",
      },
      centerLatitude: 0,
      centerLongitude: 0,
      polygons: [],
      // 新增数据
      currentTime: "",
      distance: null,
      distanceText: "",
      locationRef: null,
      isUpdateData: true,
    };
  },
  computed: {},
  components: {
    mumuGetlocation,
  },
  onLoad(options) {
    this.init();
  },
  created() {
    this.getProjectInfo();
    this.updateTime();
  },
  onUnload() {
    // 页面卸载时清除定时器
  },
  methods: {
    // 这里放置方法
    init() {
      this.$nextTick(() => {
        // 在检测用户是否开启定位权限需要一个过程，推荐使用 login 提示一下
        uni.showLoading({
          title: "定位组件加载中...",
          mask: true,
        });
        // 初始化组件，并且检测是否开启与授权定位
        this.$refs.muLocation.__init().then(
          (location) => {
            // 用户授权了和开启了定位，把定位对象保存到 data 中
            this.locationRef = location;
            // this.punchCard();
            uni.hideLoading();
            this.getLocationInfo();
          },
          (err) => {
            // 用户拒绝了定位请求，获取系统没有开启定位功能
            uni.hideLoading();
            console.log("err", err);
            if (err.code === 1) {
              uni.showModal({
                title: "获取定位权限失败",
                content:
                  "你拒绝了位置授权服务。请允许当前页面获取定位授权，后刷新页面。",
                confirmText: "去开启",
                success: (res) => {
                  if (res.confirm) {
                    this.openSetting();
                  }
                },
              });
            } else {
              uni.showModal({
                title: "获取定位权限失败",
                content:
                  "请确定手机定位已打开，并且当前浏览器允许获取定位，都开启后请刷新页面。",
              });
            }
          }
        );
      });
    },
    async getLocationInfo() {
      console.log("获取定位信息");
      let location = null;
      if (this.locationRef == null) {
        uni.showToast({ title: "定位组件未初始化", icon: "none" });
        this.init();
      }
      console.log("this.locationRef", this.locationRef);
      try {
        location = await this.locationRef.getLocation();
        // [ this.centerLongitude,this.centerLatitude] = wgs84togcj02(location.lng,location.lat);
        this.centerLatitude = location.lat;
        this.centerLongitude = location.lng;
        this.punchRange = {
          type: location.type,
          addr: location.addr,
          province: location.province,
          city: location.city,
          district: location.district,
          lat: this.centerLatitude,
          lng: this.centerLongitude,
        };
        // 获取距离信息
      } catch (err) {
        console.log("getLocationInfo", err);
        uni.showToast({ title: "获取定位失败" + err, icon: "none" });
      }
    },
    async getProjectInfo() {
      try {
        const res = await getProjectInfo({ id: this.projectId });
        if (res.code === 1) {
          console.log("项目信息获取成功", res.data);
          this.projectInfo = res.data;
          this.mapLocation = res.data.app_address;
        } else {
          uni.showToast({
            title: "获取项目信息失败",
            icon: "none",
            duration: 3000,
          });
        }
      } catch (error) {
        console.log(error);
      }
    },
    // 更新时间
    updateTime() {
      if (this.isUpdateData) {
        const now = new Date();
        const hours = now.getHours().toString().padStart(2, "0");
        const minutes = now.getMinutes().toString().padStart(2, "0");
        const seconds = now.getSeconds().toString().padStart(2, "0");
        this.currentTime = `${hours}:${minutes}:${seconds}`;
        setTimeout(this.updateTime, 1000);
      }
    },
    // 打卡
    async punchCard() {
      console.log("开始打卡");
      // console.log("this.locationRef", this.locationRef);
      // let location = null;
      if (this.centerLatitude == 0 && this.centerLongitude == 0) {
        uni.showToast({ title: "定位组件未初始化", icon: "none" });
        this.getLocationInfo();
        return;
      }

      try {
        // 获取定位成功后显示定位信息
        // location = await this.locationRef.getLocation();

        // console.log("当前位置信息:", location);

        // this.punchRange = {
        //   latitude: location.lat,
        //   longitude: location.lng,
        // };

        const res = await attendanceIn({
          userId: this.userId,
          projectId: this.projectId,
          latitude: this.centerLatitude,
          longitude: this.centerLongitude,
        });

        console.log("attendanceIn", res);
        if (res.code === 1) {
          this.isTimeSwitch = false;
          this.isUpdateData = false;
          this.distanceText = res.msg;
          uni.showToast({ title: res.msg, icon: "success" });
        } else if (res.code == -3) {
          this.distanceText = res.msg;
        } else {
          uni.showToast({ title: "打卡失败", icon: "none" });
        }
        
        this.getLocationInfo();
      } catch (err) {
        console.log("attendanceIn", err);
        uni.showToast({ title: "网络请求失败" + err, icon: "none" });
      }
    },
    openSetting() {
      uni.openSetting({
        success: (res) => {
          console.log("openSetting success", res);
          if (res.authSetting["scope.userLocation"]) {
            // 当用户开启定位权限后，重新初始化定位组件
            this.init();
          }
        },
      });
    },
    chooseVideo() {
      uni.chooseVideo({
        sourceType: ['camera'], // 只使用摄像头
        maxDuration: 10, // 最长录制时间10秒
        camera: 'front', // 使用前置摄像头
        success: (res) => {
          this.videoSrc = res.tempFilePath; // 获取视频临时路径
        },
        fail: (err) => {
          uni.showToast({
            title: '录制视频失败',
            icon: 'none'
          });
        }
      });
    },
  },
};
</script>

<style scoped>
.square-view {
  width: 100%;
  height: 400px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #e2e2e2;
}

.circle {
  width: 150px;
  height: 150px;
  border-radius: 50%;
  background-color: #ffffff;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.distance {
  margin-top: 20px;
}
</style>
